The Extract Method refactoring allows to turn a selected code fragment into a method.
To extract a code fragment into a method, first select it in the editor and invoke Refactoring | Extract Method or press Ctrl-Alt-E.
IDEA analyses the code and detects variables that are input for the selected code fragment and variables that are output for it. If there is exactly one output variable, it is used as a return value for the extracted method. In case there are multiple output variables, the Extract Method refactoring may not be applied and the error message is shown. There are a few possible solutions to allow the Extract Method work in this case. For example, you may introduce a special data-class which contains all output values. Because of great variety of such possibilities, the choice is left up to you and the Extract Method refactoring does not work with multiple output values in automatic mode, you must change your code before applying the refactoring.
|
![]() |
After you have specified the name and parameters of the method, press the "OK" button. The new method is created
and the code fragment is replaced with a method call.
The code fragment to form the method may not necessary be a set of statements, it may also be an expression used somewhere in the code. For example, applying the Extract Method to
result in
Note: In addition to the case of multiple output variables, the Extract Method refactoring will not work in a few more cases. For example, it will not work for a code fragment which conditionally returns from the containing method and is not placed at the end of it.